<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CountryModel;
use App\Models\lazada\CallBackModel;
use App\Models\lazada\OrderModel;
use App\Models\lazada\BigBagModel;
use App\Models\CNLogModel;
use App\Models\CustomerModel;
use App\Models\lazada\LogModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;


class Lazada extends Controller
{
    protected $log_id = 0;
    //验证签名和日志记录
    public function __construct(Request $request)
    {
        $action = $request->route()->getActionMethod();
        $data = $request->all();
        if($action == 'order' || $action == 'bigbag'){
            $header = $request->header();
            $header = $this->getHeader($header);
            $uri = $request->getUri();
            $uri = $this->removeDomainFromUrl($uri);

            $sign = $this->verifySign($uri, config('lazada.AccessKeyId'), config('lazada.AccessKeySecret'), $header);
//            $sign = true;

//            $log = New LogModel();
//            $log->data = json_encode($data);
//            $log->ip = $request->ip();
//            $log->type = $action;
//            $log->header = json_encode($header);
//            $log->uri = $uri;
//            $log->sign = $sign ? 1 : 0;
//            $log->platform = 'lazada';
//            $log->save();
//
//            $this->log_id = $log->id;

            if(!$sign){
                return response()->json([
                    'success' => false,
                    'errorMsg' => '签名错误'
                ]);
            }

        }

        $cache_data = [
            'type' =>$action,
            'data' => $data,
            'header' => $header,
            'uri' => $uri,
            'sign' => $sign ? 1 : 0,
            'ip' => $request->ip(),
            'time' => date('Y-m-d H:i:s')
        ];

        Redis::rpush('lazada_log', json_encode($cache_data));

    }

    /**
     * Notes:小包下发
     * User: xiangzi
     * Date: 2025/5/12
     * Time: 下午5:49
     * @return \Illuminate\Http\JsonResponse
     */
    public function order(Request $request)
    {
        $data = $request->all();

        $return = [
            'success' => true,
            'data' => [
                'orderCode' => $data['orderCode'],
            ]
        ];

        return response()->json($return);

//        $customer_id = 13;
//
//        $asn = new OrderModel();
//        $asn->platform = 'lazada';
//        $asn->customer_id = $customer_id;
//        $asn->trackingNumber = $data['trackingNumber'] ?? '';
//        $asn->receiver = isset($data['receiver']) ? json_encode($data['receiver']) : '';
//        $asn->sender = isset($data['sender']) ? json_encode($data['sender']) : '';
//        $asn->preResInfo = isset($data['preResInfo']) ? json_encode($data['preResInfo']) : '';
//        $asn->nextResInfo = isset($data['nextResInfo']) ? json_encode($data['nextResInfo']) : '';
//        $asn->parcel = isset($data['parcel']) ? json_encode($data['parcel']) : '';
//        $asn->tradeOrderId = $data['tradeInfo']['tradeOrderId'] ?? '';
//        $asn->idempotentId = $data['idempotentId'] ?? '';
//        $asn->orderCode = $data['orderCode'] ?? '';
//        $asn->features = isset($data['features']) ? json_encode($data['features']) : '';
//        $asn->taxId = $data['taxId'] ?? '';
//        $asn->fromLocation = $data['fromLocation'] ?? '';
//        $asn->toLocation = $data['toLocation'] ?? '';
//        $asn->resCode = $data['preResInfo']['resCode'] ?? '';
//        $asn->weight = $data['parcel']['weight'] ?? 0;
//        $asn->price = $data['parcel']['price'] ?? 0;
//        $asn->priceUnit = $data['parcel']['priceUnit'] ?? '';
//
//        //目的地国家
//        if(isset($data['receiver']['address']['country'])){
////            $des_find = CountryModel::where('erzi_code', $data['receiver']['address']['country'])->first();
////            $asn->des_country_id = $des_find->id ?? 0;
//            $asn->des_country_code = $data['receiver']['address']['country'];
//        }
//
//        //货物属性
//        if(isset($data['parcel']['goodsList'])){
//            $asn->goods_attr = $data['parcel']['goodsList'][0]['cargoType'] ?? 1;
//        }
//
//        //目的地机场
//        if($data['toLocation']){
//            $arr = explode(' ', $data['toLocation']);
//            if(count($arr) > 1){
//                $asn->destination = $arr[1];
//            }else{
//                $asn->destination = $data['toLocation'];
//            }
//        }
//
//        $asn->log_id = $this->log_id;
//        $asn->save();
//
//        $return = [
//            'success' => true,
//            'data' => [
//                'orderCode' => $asn->orderCode,
//            ]
//        ];
//
//        return response()->json($return);
    }

    /**
     * Notes:大包下发
     * User: xiangzi
     * Date: 2025/5/12
     * Time: 下午5:49
     * @return \Illuminate\Http\JsonResponse
     */
    public function bigbag(Request $request)
    {
        $data = $request->all();

        $return = [
            'success' => true,
        ];

        return response()->json($return);

//        $return = [
//            'success' => true
//        ];
//
//        $customer_id = 13;
//
//        $notify = new BigBagModel();
//        $notify->platform = 'lazada';
//        $notify->customer_id = $customer_id;
//        $notify->parcelList = isset($data['parcelList']) ? json_encode($data['parcelList']) : '';
//        $notify->bigBagID = $data['bigBagID'];
//        $notify->parcelQty = $data['parcelQty'];
//        $notify->trackingNumber = $data['trackingNumber'];
//        $notify->features = isset($data['features']) ? json_encode($data['features']) : '';
//        $notify->bigBagWeight = $data['bigBagWeight'] ?? 0;
//        $notify->weightUnit = $data['weightUnit'] ?? '';
//        $notify->bigBagVolume = $data['bigBagVolume'] ?? 0;
//        $notify->bigBagLength = $data['bigBagLength'] ?? 0;
//        $notify->bigBagWidth = $data['bigBagWidth'] ?? 0;
//        $notify->bigBagHeight = $data['bigBagHeight'] ?? 0;
//        $notify->dimensionUnit = $data['dimensionUnit'] ?? '';
//        $notify->cargoType = $data['cargoType'] ?? 0;
//        $notify->fromLocation = $data['fromLocation'] ?? '';
//        $notify->toLocation = $data['toLocation'] ?? '';
//
//
//        //更新小包的打包号
//        if(isset($data['parcelList'])){
//            $orderCode = [];
//            foreach ($data['parcelList'] as $parcel){
//                $orderCode[] = $parcel['orderCode'];
//
////                $order = OrderModel::where('orderCode', $parcel['orderCode'])->first();
////                if($order){
////                    $order->bigBagID = $notify->bigBagID;
////                    $notify->des_country_id = $order->des_country_id;
////                    $order->save();
////                }
//            }
//
//            OrderModel::whereIn('orderCode', $orderCode)->update([
//                'bigBagID' => $notify->bigBagID
//            ]);
//        }
//
//        //目的地机场
//        if($data['toLocation']){
//            $arr = explode(' ', $data['toLocation']);
//            if(count($arr) > 1){
//                $notify->destination = $arr[1];
//            }else{
//                $notify->destination = $data['toLocation'];
//            }
//        }
//
//        $notify->log_id = $this->log_id;
//        $notify->save();
//
//
//        return response()->json($return);
    }







    public function verifySign($uri, $accessKeyId, $accessKeySecret, $headers)
    {
        $uri = $this->removeDomainFromUrl($uri);
        $authentication = $headers['authorization'] ?? '';
        // 是否为空
        if (empty($authentication)) {
//            echo 'Authorization header is null';
            return false;
        }

        $signMethod = 'ACS3-HMAC-SHA256';
        $elementsArr = explode(',',substr($authentication, strlen($signMethod) + 1));
        $elementMap = [];
        foreach ($elementsArr as $element) {
            $arr = explode('=', $element);
            $elementMap[$arr[0]] = $arr[1];
        }

        $credential = $elementMap['Credential'] ?? '';
        $signedHeaderStr = $elementMap['SignedHeaders'] ?? '';
        $signedHeader = explode(';', $signedHeaderStr);
        $reqSignature = $elementMap['Signature'] ?? '';

        if ($credential != $accessKeyId) {
//            echo "$credential not equal to $accessKeyId";
            return false;
        }

        $arr = explode('?', $uri);

        $message = "POST\n" . $arr[0] . "\n" ;
        if (sizeof($arr) > 1) {
            $message .= rawurldecode($arr[1]);
        }
        $message .= "\n";
        foreach ($signedHeader as $key) {
            $message .= $key . ':' . $headers[$key] . "\n";
        }

        $message .= "\n" . $signedHeaderStr . "\n";
        $message .= $headers["x-acs-content-sha256"];

        $stringToSign = $signMethod . "\n" . hexHash($message);
        $signature = bin2hex(hash_hmac('sha256', $stringToSign, $accessKeySecret, true));

//        echo $signature . ' = ' .  $reqSignature;
        return $signature == $reqSignature;
    }

    public function check_sign(Request $request)
    {

        $id = $request->input('id');

//        $data = CallBackModel::find($id);
//        var_dump(json_decode($data->return, true));exit();

        $data = LogModel::find($id);

        if(!$data){
            return $this->error('数据不存在');
        }
        var_dump(json_decode($data->header, true));

        $header = $this->getHeader(json_decode($data->header, true));
        $res = $this->verifySign($data->uri, config('lazada.AccessKeyId'), config('lazada.AccessKeySecret'), $header);

        return $this->success($res);
    }


    public function getHeader($header)
    {
        $return = [];
        foreach ($header as $key => $value){
            if(is_array($value)){
                $return[$key] = $value[0];
            }else{
                $return[$key] = $value;
            }
        }
        return $return;
    }

    function removeDomainFromUrl($url) {
        $parsedUrl = parse_url($url);

        if(isset($parsedUrl['query'])){
            $arr = explode('&', $parsedUrl['query']);
            foreach ($arr as $key => $value){
                if(strpos($value, 's=') !== false){
                    unset($arr[$key]);
                }
            }
            $parsedUrl['query'] = implode('&', $arr);
        }

        $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
        $query = isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '';
        $fragment = isset($parsedUrl['fragment']) ? '#' . $parsedUrl['fragment'] : '';

        return $path . $query . $fragment;
    }

}
